/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package me.linkcn.ydtxl.client.activity;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.fsck.k9.activity.Accounts;

import me.linkcn.ydtxl.client.Consts;
import me.linkcn.ydtxl.client.R;
import me.linkcn.ydtxl.client.sync.object.Group;
import me.linkcn.ydtxl.client.util.ContactHelper;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;

/**
 * @author icer.He
 *
 */
public class MultiActivity extends Activity {
	
	private GroupListItemAdapter gAdapter;
	
	private View selectedGroupView = null;
	
	private HashSet<Long> selectedContact = new HashSet<Long>();
	
    @Override
    public void onCreate(Bundle savedInstanceState)  {

    	super.onCreate(savedInstanceState);
        Log.d(Consts.TAG, "MainActivity create");
        //初始化主画面
        show();
    }
    
    private void show() {
    	setContentView(R.layout.multi);
    	//绑定按钮
    	//主画面
	    final Button main = (Button) findViewById(R.id.main);
	    main.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {		
				Intent intent = new Intent(MultiActivity.this, MainActivity.class);
				startActivity(intent);
			}
        });
	    
	    //收藏联系人画面
	    final Button fav = (Button) findViewById(R.id.fav);
	    fav.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {		
				Intent intent = new Intent(MultiActivity.this, FavActivity.class);
				startActivity(intent);
			}
        });
	    
	    //邮件(暂时)
	    final Button mail = (Button)findViewById(R.id.mail);
	    mail.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {		
				Intent intent = new Intent(MultiActivity.this, Accounts.class);
				startActivity(intent);
			}
        });
	    
	  //显示分组列表
    	final ListView glist = (ListView) findViewById(R.id.group_list);
    	Cursor cursor = getContentResolver().query(Groups.CONTENT_URI,null,Groups.DELETED+"=0",null,null);
    	List<Group> localGroupList = new ArrayList<Group>();
    	localGroupList.add(ContactHelper.getAllGroup(this));
    	for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {  
    		Log.d("GROUP_NAME", cursor.getString(cursor.getColumnIndex(Groups.TITLE)));
    		Log.d("GROUP_ID", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups._ID))));
    		Log.d("VERSION", String.valueOf(cursor.getLong(cursor.getColumnIndex(Groups.VERSION))));
    		localGroupList.add(ContactHelper.getGroup(cursor));
    	} 
    	startManagingCursor(cursor);
    	gAdapter = new GroupListItemAdapter(this, R.layout.group_item, cursor);
        glist.setAdapter(gAdapter);
        
        //显示全部联系人列表
    	final ListView list = (ListView) findViewById(R.id.contacts_list);
    	String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
	        + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
	        + Contacts.DISPLAY_NAME + " != '' ))";
    	Cursor c =
	        getContentResolver().query(Contacts.CONTENT_URI, Consts.CONTACTS_SUMMARY_PROJECTION, select,
	        null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    	startManagingCursor(c);
    	MultiContactListItemAdapter adapter = new MultiContactListItemAdapter(this, R.layout.multi_list_item, c);
        list.setAdapter(adapter);
    }
    
    /**
     * 显示联系人列表
     * @param groupId
     */
    private void showContactList(long groupId) {
    	final ListView list = (ListView) findViewById(R.id.contacts_list);
    	
    	if (5 == groupId) { //收藏
    		String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
		        + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
		        + Contacts.DISPLAY_NAME + " != '' )) AND ("
		        + Contacts.STARRED + "=1)";
		        
			Cursor c =
		        getContentResolver().query(Contacts.CONTENT_URI, Consts.CONTACTS_SUMMARY_PROJECTION, select,
		        null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
			startManagingCursor(c);
			MultiContactListItemAdapter adapter = new MultiContactListItemAdapter(this, R.layout.multi_list_item, c);
		    list.setAdapter(adapter);
    	} else {
	    	Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, 
	    			  new String[] { ContactsContract.Data.RAW_CONTACT_ID },
	    			  ContactsContract.Data.MIMETYPE+" = '"+GroupMembership.CONTENT_ITEM_TYPE
	    			  +"' AND "+ContactsContract.Data.DATA1+"="+ groupId, 
	    			  null, null);
	    	StringBuilder inSelectionBff = new StringBuilder(RawContacts._ID).append(" IN ( 0");
	    	for (cursor.moveToFirst();!(cursor.isAfterLast());cursor.moveToNext()) {      		
	    		inSelectionBff.append(',').append(cursor.getLong(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID)));
	    	}
	    	inSelectionBff.append(')');
	    	cursor.close();
	    	
	    	Cursor contactIdCursor = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
	    			  new String[] { ContactsContract.RawContacts.CONTACT_ID }, inSelectionBff.toString(), null, null);
	    	inSelectionBff = new StringBuilder(Contacts._ID).append(" IN ( 0");
	    	for (contactIdCursor.moveToFirst();!(contactIdCursor.isAfterLast());contactIdCursor.moveToNext()) {      		
	    		inSelectionBff.append(',').append(contactIdCursor.getLong(contactIdCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID)));
	    	}
	    	inSelectionBff.append(')');
	    	contactIdCursor.close();
	    	
	    	
	    	String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
		        + Contacts.HAS_PHONE_NUMBER + "=1) AND ("
		        + Contacts.DISPLAY_NAME + " != '' )) AND "
		        + inSelectionBff.toString();
			Cursor c =
		        getContentResolver().query(Contacts.CONTENT_URI, Consts.CONTACTS_SUMMARY_PROJECTION, select,
		        null, Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
			startManagingCursor(c);
			MultiContactListItemAdapter adapter = new MultiContactListItemAdapter(this, R.layout.multi_list_item, c);
		    list.setAdapter(adapter);
    	}
    	
    }
    
    /**
     * 组列表Adapter
     * @author icer.He
     *
     */
    private final class GroupListItemAdapter extends ResourceCursorAdapter {

        public GroupListItemAdapter(Context context, int layout, Cursor c) {
            super(context, layout, c);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            final GroupListItemCache cache = (GroupListItemCache) view.getTag();
            long groupId = cursor.getLong(cursor.getColumnIndex(Groups._ID));
            String groupName = cursor.getString(cursor.getColumnIndex(Groups.TITLE));
            
            cache.id = groupId;
            if (Consts.groupName.containsKey(groupName)) {
            	cache.nameView.setText(Consts.groupName.get(groupName));
            } else {
            	cache.nameView.setText(groupName);
            }
            
            view.setOnClickListener(new OnClickListener() {//点击分组动作

				@Override
				public void onClick(View v) {
					//显示选中组中的联系人
					//Toast.makeText(MainActivity.this,"Id:"+cache.id+" Name:"+cache.nameView.getText(), Toast.LENGTH_LONG).show();
					showContactList(cache.id);
				}
            	
            });
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View view = super.newView(context, cursor, parent);
            GroupListItemCache cache = new GroupListItemCache();
            cache.nameView = (TextView) view.findViewById(R.id.group_name);
            view.setTag(cache);

            return view;
        }
        
        final class GroupListItemCache {
        	public long id;
            public TextView nameView;
        }
    }
    
    /**
     * 联系人多选列表Adapter
     * @author icer.He
     *
     */
    private class MultiContactListItemAdapter extends ResourceCursorAdapter {
    	
    	static final int SUMMARY_ID_COLUMN_INDEX = 0;
    	static final int SUMMARY_NAME_COLUMN_INDEX = 1;
    	static final int SUMMARY_STARRED_COLUMN_INDEX = 2;
    	static final int SUMMARY_TIMES_CONTACTED_COLUMN_INDEX = 3;
    	static final int SUMMARY_PRESENCE_STATUS_COLUMN_INDEX = 4;
    	static final int SUMMARY_PHOTO_ID_COLUMN_INDEX = 5;
    	static final int SUMMARY_LOOKUP_KEY = 6;
    	static final int SUMMARY_HAS_PHONE_COLUMN_INDEX = 7;
    	
    	public MultiContactListItemAdapter(Context context, int layout, Cursor c) {
    		super(context, layout, c);
    	}

    	@Override
    	public void bindView(View view, Context context, Cursor cursor) {
    		final ContactListItemCache cache = (ContactListItemCache) view.getTag();
    		//contact id
    		final long contactId = cursor.getLong(SUMMARY_ID_COLUMN_INDEX);
    		// contact name
    		cursor.copyStringToBuffer(SUMMARY_NAME_COLUMN_INDEX, cache.nameBuffer);
    		int size = cache.nameBuffer.sizeCopied;
    		cache.nameView.setText(cache.nameBuffer.data, 0, size);
    		//contact photo
    		final Uri contactUri = ContentUris.withAppendedId(
    				ContactsContract.Contacts.CONTENT_URI, contactId);
    		InputStream input = ContactsContract.Contacts
    				.openContactPhotoInputStream(context.getContentResolver(), contactUri);
    		if (null != input) {
    			cache.photoView.setImageBitmap(BitmapFactory.decodeStream(input));
    		} else {
    			cache.photoView.setImageResource(R.drawable.ic_contact_picture);
    		}
    		//checkbox
    		cache.checked.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					Long cid = Long.valueOf(contactId);
					if (isChecked) {
						selectedContact.add(cid);
					} else {
						selectedContact.remove(cid);
					}
				}	
    		});
    		
    		
    		view.setOnClickListener(new OnClickListener() {
    			@Override
    			public void onClick(View arg0) {
    				cache.checked.setChecked(!cache.checked.isChecked());
    			}

    		});
    	}

    	@Override
    	public View newView(Context context, Cursor cursor, ViewGroup parent) {
    		View view = super.newView(context, cursor, parent);
    		ContactListItemCache cache = new ContactListItemCache();
    		cache.checked = (CheckBox)view.findViewById(R.id.checked);
    		cache.nameView = (TextView) view.findViewById(R.id.name);
    		cache.photoView = (ImageView) view.findViewById(R.id.photo);
    		view.setTag(cache);

    		return view;
    	}    
        
        final class ContactListItemCache {
        	public CheckBox checked;
            public TextView nameView;
            public ImageView photoView;
            public CharArrayBuffer nameBuffer = new CharArrayBuffer(128);
        }
    }

}
